//
//  APLoginViewController.m
//  AqualPolo
//
//  Created by dong on 2024/5/1.
//

#import "APLoginViewController.h"
#import "APLoginView.h"
#import "APWebViewController.h"
#import <AuthenticationServices/AuthenticationServices.h>
#import "APLoginPrivacyPolicyController.h"
#import "APLoginPrivacyPolicyController.h"
#import "APLoginManager.h"
#import "APTabBarViewController.h"
#import "AppDelegate.h"
#import "APUUIDManager.h"

@interface APLoginViewController ()<APProtocolControlProtocol,ASAuthorizationControllerDelegate,ASAuthorizationControllerPresentationContextProviding>
@property (nonatomic, strong) APLoginView *loginView;
@property (nonatomic, assign) bool isChecked;
@end

@implementation APLoginViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess:) name:LoginSuccessNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginFail:) name:LoginFailNotification object:nil];
    }
    return self;
}


- (APLoginView *)loginView{
    if (!_loginView) {
        _loginView = [[APLoginView alloc] init];
        [_loginView.appleLoginButton addTarget:self action:@selector(appleLoginButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [_loginView.fastLoginButton addTarget:self action:@selector(fastLoginButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        _loginView.protocolControl.delegate = self;
    }
    return _loginView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _isChecked = false;
    [self loadBackground:@"login_bg"];
    [self.view addSubview:self.loginView];
    [self.loginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    [APDataManager netWorkStatusChanged:^(DMNetWorkStatus status) {}];
}

- (void)loginSuccess:(NSNotification *)noti{
    [self.view removeProgress];
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (![app.window.rootViewController isKindOfClass:[APTabBarViewController class]]) {
        app.window.rootViewController  = [[APTabBarViewController alloc] init];
    }
    [APLogManager statisticWithPage:APPage_loginSuccess];
}

- (void)loginFail:(NSNotification *)noti{
    [self.view removeProgress];
    [self.view ShowProgressOnlyLabel:noti.object];

}


- (void)appleLoginButtonDidClick:(APLoginButton *)sender{
    if (!_isChecked) {
        APLoginPrivacyPolicyController *vc = [[APLoginPrivacyPolicyController alloc] init];
        [vc setContinueClickCallBack:^{
            [self appleLogin];
        }];
        [self presentViewController:vc animated:true completion:nil];
        return;
    }

    [self appleLogin];
}

- (void)fastLoginButtonDidClick:(APLoginButton *)sender{
    if (!_isChecked) {
        APLoginPrivacyPolicyController *vc = [[APLoginPrivacyPolicyController alloc] init];
        [vc setContinueClickCallBack:^{
            [self fastLogin];
        }];
        [self presentViewController:vc animated:true completion:nil];
        return;
    }
    [self fastLogin];

}

- (void)fastLogin{
    [self.loginView.protocolControl setCheckSelectedStatus:true];
    _isChecked = true;
    NSString *uuid = [APUUIDManager dm_getUUID];
    [self.view ShowProgress];
    [[APLoginManager shareInstance] loginWithToken:uuid oauthType:4];
    [APLogManager statisticWithPage:APPage_quickLogin];
}

- (void)appleLogin{
    [self.loginView.protocolControl setCheckSelectedStatus:true];
    _isChecked = true;
    [APLogManager statisticWithPage:APPage_appleLogin];
    if (@available(iOS 13.0, *)) {
        ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
        ASAuthorizationAppleIDRequest *appleIDRequest = [appleIDProvider createRequest];
        appleIDRequest.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
        ASAuthorizationController *authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[appleIDRequest]];
        authorizationController.delegate = self;
        authorizationController.presentationContextProvider = self;
        [authorizationController performRequests];
    }else{
        LYLog(@"error");
    }
}

/// 授权成功回调
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)){
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        ASAuthorizationAppleIDCredential *appleIDCredential = authorization.credential;
        NSData *identityToken = appleIDCredential.identityToken;
        // 服务器验证需要使用的参数
        NSString *identityTokenStr = [[NSString alloc] initWithData:identityToken encoding:NSUTF8StringEncoding];
        [[APLoginManager shareInstance] loginWithToken:identityTokenStr oauthType:3];

    }else if ([authorization.credential isKindOfClass:[ASPasswordCredential class]]){
        // 这个获取的是iCloud记录的账号密码，需要输入框支持iOS 12 记录账号密码的新特性，如果不支持，可以忽略
        ASPasswordCredential *passwordCredential = authorization.credential;
        NSString *user = passwordCredential.user;
        NSString *password = passwordCredential.password;
        
    }else{
        LYLog(@"授权信息不符");
    }
}

/// 授权失败回调
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)){
    NSLog(@"Handle error：%@", error);
    NSString *errorMsg = nil;
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = @"用户取消了授权请求";
            break;
        case ASAuthorizationErrorFailed:
            errorMsg = @"授权请求失败";
            break;
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = @"授权请求响应无效";
            break;
        case ASAuthorizationErrorNotHandled:
            errorMsg = @"未能处理授权请求";
            break;
        case ASAuthorizationErrorUnknown:
            errorMsg = @"授权请求失败未知原因";
            break;
        default:
            break;
    }
    LYLog(@"errorMsg = %@", errorMsg);
}

/// 设置展示内容给用户的Window
- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)){
    return [UIApplication sharedApplication].windows.lastObject;
}


- (void)termofUseDidClick{
    APWebViewController *webVC = [[APWebViewController alloc] init];
    webVC.urlString = Term_Use__URL;
    webVC.titleString = Term_of_Use_title;
    [self presentViewController:webVC animated:true completion:nil];
}

- (void)privacyPolicyDidClick{
    APWebViewController *webVC = [[APWebViewController alloc] init];
    webVC.urlString = Privacy_Policy_URL;
    webVC.titleString = Privacy_Policy_title;
    [self presentViewController:webVC animated:true completion:nil];
}

- (void)checkButtonDidClick:(BOOL)isChecked{
    _isChecked = isChecked;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:LoginSuccessNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:LoginFailNotification object:nil];

}
@end
